package com.alan.camunda.boot.groovymod.compiled;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

public class CompiledDemo1 {

    private static GroovyShell shell = new GroovyShell();

    // 编译并缓存脚本
    public static Script compileScript(String script) {
        return shell.parse(script);
    }

    // 执行脚本
    public static Object executeScript(Script script, Binding binding) {
        script.setBinding(binding);
        return script.run();
    }

    public static void main(String[] args) {
        // 定义脚本
        String script = """
            import static com.alan.camunda.boot.util.StringFunctions.*
            def bizLogic() {
                return "Hello, " + name
            }
            return bizLogic()
        """;

        // 编译并缓存脚本
        Script compiledScript = compileScript(script);
        Script c2 = compileScript(script);
        Script c3 = compileScript(script);
        System.out.println(compiledScript.getClass());
        System.out.println(c2.getClass());
        System.out.println(c3.getClass());

        // 绑定变量
        Binding binding = new Binding();
        binding.setVariable("name", "Alex");

        // 执行脚本
        Object result = executeScript(compiledScript, binding);

        // 输出结果
        System.out.println("Groovy script result: " + result);
    }


}
